import javax.swing.*;
import java.util.*;

public class BinaryTree {

    static class TreeNode{
        private char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode creatTree(){
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }

    //二叉树遍历 创建
    public static int i = 0;
    public static  TreeNode creatTree(String str){
        TreeNode root = null;
        if(str.charAt(i) != '#'){
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = creatTree(str);
            root.right = creatTree(str);
        }else{
            i++;
        }
        return root;
    }

    // 前序遍历
    public void preOrder(TreeNode root){
        if (root == null){
            return;
        }
        System.out.print(String.valueOf(root.val) + " ");
        preOrder(root.left);
        preOrder(root.right);

    }

    //前序遍历非递归
    public void preOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    //遍历思路
    List<Character> list = new ArrayList<>();
    public List<Character> preorderTraversal(TreeNode root) {
        if (root == null){
            return list;
        }

        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);

        return list;
    }

    //子问题思路
    public List<Character> preorderTraversalChild(TreeNode root){
        List<Character> list = new ArrayList<>();
        if (root == null){
            return list;
        }

        list.add(root.val);
        List<Character> listLeft = preorderTraversalChild(root.left);
        list.addAll(listLeft);

        List<Character> listRight = preorderTraversalChild(root.right);
        list.addAll(listRight);

        return  list;
    }

    // 中序遍历
    public void inOrder(TreeNode root){
        if (root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(String.valueOf(root.val) + " ");
        inOrder(root.right);
    }


    //中序遍历非递归
    public void inOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur =  top.right;
        }
    }


    // 后序遍历
    public void postOrder(TreeNode root){
        if (root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(String.valueOf(root.val) + " ");
    }


    //后序遍历非递归
    public void postOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;

        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev){
                System.out.print(top.val + " ");
                stack.pop();
                prev = top;
            }else {
                cur = top.right;
            }
        }
    }


    // 获取树中节点的个数
    public int usedSize;
    public void size(TreeNode root){
        if(root == null){
            return;
        }
        usedSize++;
        size(root.left);
        size(root.right);
    }

    //子问题思路
    public int size1(TreeNode root){
        if (root == null){
            return 0;
        }
        return size1(root.left) + size1(root.right) + 1;
    }

    // 获取叶子节点的个数
    public int size;
    public void getLeafNodeCount(TreeNode root){
        if (root == null){
            return;
        }
        if (root.left == null && root.right == null){
            size++;
            return;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    // 子问题思路-求叶子结点个数
    public int getLeafNodeCount1(TreeNode root){
        if (root == null){
            return 0;
        }
        if (root.left == null && root.right == null){
            return 1;
        }
        return getLeafNodeCount1(root.left)
                + getLeafNodeCount1(root.right);
    }

    // 获取第K层节点的个数
    public int count;
    public int getKLevelNodeCount(TreeNode root,int k){
        if (root == null){
            return 0;
        }
        if (k == 1 ){
            count++;
        }
        getKLevelNodeCount(root.left,k-1);
        getKLevelNodeCount(root.right,k-1);
        return count;
    }

    public int getKLevelNodeCount1(TreeNode root,int k){
        if (root == null){
            return 0;
        }
        if (k == 1){
            return 1;
        }
        return getKLevelNodeCount1(root.left,k-1)
                + getKLevelNodeCount1(root.right,k-1);
    }

    // 获取二叉树的高度
    public int getHeight(TreeNode root){
        if (root == null){
            return 0;
        }
        return Math.max(getHeight(root.left),getHeight(root.right)) + 1;
    }

    // 检测值为value的元素是否存在
    public TreeNode find(TreeNode root, char val){
        if (root == null){
            return null;
        }
        if (root.val == val){
            return root;
        }

        TreeNode letfT = find(root.left,val);
        if (letfT != null){
            return letfT;
        }
        TreeNode rightT = find(root.right,val);
        if (rightT != null){
            return rightT;
        }
        return null;
    }

    //给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同。
    //
    //如果两个树在结构上相同，并且节点具有相同的值，则认为它们是相同的。
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p != null && q == null || p == null && q != null){
            return false;
        }
        if (p == null && q == null){
            return true;
        }
        if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left,q.left)
                && isSameTree(p.right,q.right);
    }

    //给你两棵二叉树 root 和 subRoot 。
    // 检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。
    // 如果存在，返回 true ；否则，返回 false 。
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null){
            return false;
        }
        if (isSameTree(root,subRoot)){
            return true;
        }
        if (isSubtree(root.left,subRoot)){
            return true;
        }
        if (isSubtree(root.right,subRoot)){
            return true;
        }
        return false;
    }


    //给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。
    public TreeNode invertTree(TreeNode root) {
        if (root == null){
            return null;
        }
        if(root.left == null && root.right == null){
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //给你一个二叉树的根节点 root ， 检查它是否轴对称。
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }

        return isSymmetricChild(root.left,root.right);
    }

    private boolean isSymmetricChild(TreeNode leftNode, TreeNode rightNode) {
        //1.判断结构是否相等
        if (leftNode == null && rightNode != null || leftNode != null && rightNode == null){
            return false;
        }
        if (leftNode == null && rightNode == null){
            return true;
        }
        //2.判断值是否相等
        if (leftNode.val != rightNode.val){
            return false;
        }

        return isSymmetricChild(leftNode.left,rightNode.right)
                && isSymmetricChild(leftNode.right, rightNode.left);
    }

    //层序遍历
    public void levelOrder(TreeNode root){
        if (root == null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.print( cur.val + " ");
            if (cur.left != null){
                queue.offer(cur.left);
            }
            if (cur.right != null){
                queue.offer(cur.right);
            }
        }
        System.out.println();

    }

    public List<List<Character>> levelOrder1(TreeNode root) {
        List<List<Character>> list = new LinkedList<List<Character>>();
        if (root == null){
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            List<Character> list2 = new LinkedList<Character>();
            int size = queue.size();
            while(size != 0){
                TreeNode cur = queue.poll();
                list2.add(cur.val);
                if (cur.left != null){
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
                size--;
            }
            list.add(list2);
        }
        return list;
    }
    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root){
        if (root == null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if (cur != null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
        while (!queue.isEmpty()){
            TreeNode peek = queue.peek();
            if (peek != null){
                return false;
            }
            queue.poll();
        }
        return true;
    }

    //给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return null;
        }
        if(p == root || q == root){
            return root;
        }

        TreeNode rootLeft = lowestCommonAncestor(root.left,p,q);
        TreeNode rootRight = lowestCommonAncestor(root.right,p,q);

        if(rootLeft != null && rootRight != null){
            return root;
        }else if(rootLeft != null){
            return rootLeft;
        }else{
            return rootRight;
        }
        //return rootLeft == null ? rootRight : rootLeft;
    }

    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null){
            return null;
        }
        if(p == root || q == root){
            return root;
        }
        //1.找到路径上的所有节点
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        stackStore(root,p,stackP);
        stackStore(root,q,stackQ);
        //2.比较两个栈的大小，多的出differ个
        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        int differ = sizeP - sizeQ;
        if (differ > 0){
            while (differ > 0){
                stackP.pop();
                differ--;
            }
        }else {
            differ = sizeQ - sizeP;
            while (differ > 0){
                stackQ.pop();
                differ--;
            }
        }
        //3.每次出数据，看栈顶元素是否一样
        while (!stackP.isEmpty()){
            if (stackP.peek().val == stackQ.peek().val){
                return stackP.peek();
            }
            stackP.pop();
            stackQ.pop();
        }
        return null;
    }

    private boolean stackStore(TreeNode root, TreeNode goal,
                                       Stack<TreeNode> stack) {
        if (root == null){
            return false;
        }
        stack.push(root);
        if (root == goal){
            return true;
        }
        boolean ret = stackStore(root.left,goal,stack);
        if (ret){
            return true;
        }
        ret = stackStore(root.right,goal,stack);
        if (ret){
            return true;
        }

        stack.pop();
        return false;
    }

    //通过前序遍历和中序遍历创建二叉树
    public int preIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0 , inorder.length - 1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbenin,int inend){
        if(inbenin > inend){
            return null;
        }

        TreeNode root = new TreeNode((char) preorder[preIndex]);
        int index = findVal(inorder,inbenin,inend,preorder[preIndex]);
        preIndex++;
        root.left = buildTreeChild(preorder,inorder,inbenin,index-1);
        root.right = buildTreeChild(preorder,inorder,index+1,inend);

        return root;
    }

    public int findVal(int[] inorder,int inbenin,int inend,int val ){
        for (int i = inbenin;i <= inend ; i++){
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

    //中序遍历和后序遍历创建二叉树
    public int postIndex;//= postorder.length - 1;
    public TreeNode buildTree1(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        //postIndex 不能再方法外赋值，postorder是参数，无法再方法外调用,所以为了达到效果，
        // 直接在方法第一行对postIndex赋值即可；
        return buildTreeChild1(inorder,postorder,0,inorder.length - 1);
    }

    public TreeNode buildTreeChild1(int[] inorder, int[] postorder,int inbefore,int inend){
        if(inbefore > inend){
            return null;
        }

        TreeNode root = new TreeNode((char)postorder[postIndex]);
        int index = findVal1(inorder,inbefore,inend,postorder[postIndex]);
        postIndex--;

        root.right = buildTreeChild(inorder,postorder,index + 1,inend);
        root.left = buildTreeChild(inorder,postorder,inbefore,index - 1);

        return root;
    }

    public int findVal1(int[] inorder,int inbefore,int inend,int val){
        for(int i = inbefore; i <= inend; i++){
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

    //根据二叉树创建字符串
    public String tree2str(TreeNode root) {
        if(root == null){
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root , StringBuilder stringBuilder){
        if(root == null){
            return;
        }

        stringBuilder.append(root.val);
        if(root.left != null){
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else{
            if(root.right != null){
                stringBuilder.append("()");
            }else{
                return;
            }
        }

        if(root.right != null){
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else{
            return;
        }
    }

}
